import config from '@/utils/config' // 共通config文件
import http from '@/request/http'; // 请求

const vueUtil = {
  data() {
    return {
      /****  共通数据 *****/
      // 对话框宽度
      labelWidth:"100px",
      // 查询条件-分页
      page: {pageNum: 1,pageSize: 15,pageCount:0},
      /****  utile数据 *****/
      vueUtil:{},
      tools:tools,
    }
  },
  // 在这个例子中， mounted() 方法将在组件被挂载到DOM后调用
  mounted() {
  },
  methods:{
    //////////////////  用户相关  //////////////////////////////
    chechLoginUserType(paramType){
      let loginToken = tools.getLoginTokenJson();
      if(null == loginToken) return false;
      return loginToken.type == paramType;
    },
    //////////////////  输入限制  //////////////////////////////
    utilElInputNumber(e,paramNum){
      let value = e.target.value;
      if(!value) return ;
      if(value.split(".").length > 2){
        value = value.substr(0, value.length - 1); // 多个【.】，去除末尾
      }else if(value.substr(-1) == "."){
        // 单独的【.】，不处理
      }else{
        // 其他，数字化
        // value = tools.toNumber(value, paramNum);
        value = value.replace(/[^\d.]/g,'');
        if(value.indexOf(".") != -1 && paramNum > 0){
          value = value.substr(0, value.indexOf(".") + paramNum + 1)
        }
      }
      // 数字限制处理
      e.target.value = value;
    },
    //////////////////  取得路由  //////////////////////////////
    utilGetRouterList(){
      let self = this;
      // 取得子部分
      let obj = self.$router.options.routes.find((obj)=>{return obj.path == "/";});
      if(!obj || !obj.children){
        return [];
      }
      // return obj.children.map((obj)=>{return obj.path}).filter((obj)=>{return obj != "/"});
      return obj.children.map((obj)=>{return obj.path});
    },
    //////////////////  选择器辅助  //////////////////////////////
    utilElSelectOptionList(paramType, paramData, conf){
      // 方法：查询返回结果的map处理
      let fnResMap = (val)=> {
        let retObj = {};
        retObj["label"] = val[selectConf.label];
        retObj["value"] = val[selectConf.value];
        if(selectConf.id){
          retObj["id"] = val[selectConf.id];
        }
        if(selectConf.children && val[selectConf.children]){
          retObj["children"] = val[selectConf.children].map(fnResMap);
        }
        return retObj;
      };
      // 处理
      let self = this;
      let selectConf = Object.assign(self.elSelect[paramType], conf);
      if(!selectConf) console.log("选择器配置参数取得失败，请确认");
      // 判断是否存在缓存
      if(selectConf && selectConf.cache){
        let cache = sessionStorage.getItem(selectConf.cache);
        if(cache){
          selectConf.data = JSON.parse(cache);
          return ;
        }
      }
      // 请求处理
      http({
        url: selectConf.url,
        data: Object.assign({},selectConf.param,paramData)
      }).then(res => {
        if(selectConf && selectConf.value && selectConf.label){
          selectConf.data = res.detail.map(fnResMap);
        }else {
          selectConf.data = res.detail;
        }
        self.$set(self.elSelect,'paramType', selectConf);
        // 额外配置
        if(selectConf.all) selectConf.data.unshift({value:"",label:(selectConf.allLabel ? selectConf.allLabel : "全部")});
        // 缓存
        if(selectConf.cache){
          sessionStorage.setItem(selectConf.cache, JSON.stringify(selectConf.data));
        }
        // 成功时处理
        if(selectConf.successFun) selectConf.successFun(res, self);
      });
    },
    // 懒加载
    utilElSelectLazy(paramType, paramData){
      let self = this;
      let selectConf = self.elSelect[paramType];
      if(!selectConf) console.log("选择器配置参数取得失败，请确认");
      selectConf.option = {
        emitPath:false,
        lazy: true,
        lazyLoad:function(node, resolve){
          console.log(node);
          const { level } = node;
          http({
            url: selectConf.url, data:{level:level, code: node.value}
          }).then(res => {
            resolve(res.detail.map((obj)=>{return {value: obj.value, label: obj.label, leaf: level >= 2}}));
          });
        }
      }
    },
    // 选择器取得对应的标签
    utilElSelectFilterShow(paramType, key){
      let self = this;
      let selectConf = self.elSelect[paramType];
      if(!selectConf) console.log("选择器配置参数取得失败，请确认");
      // 筛选取得
      let value = selectConf.value || "value";
      let label = selectConf.label || "label";
      let selectObj = selectConf.data.find((obj) => {return String(obj[value]) == String(key);});
      if(selectObj){
        return selectObj[label];
      }
      return "";
    },
    //////////////////  表格分页  //////////////////////////////
    utilElTableSizeChange(pageSize){this.page.pageSize = pageSize;},
    utilElTableCurrentChange(pageNum){this.page.pageNum = pageNum;},
    utilElTableDataShow(conf){
      let self = this;
      // 分页
      let page = self.page;
      if(conf && conf.page) page = self[conf.page];
      // 数据体
      var tableDataParent = self;
      if(conf && conf.table) tableDataParent = self[conf.table];
      // 数据处理
      if (page && page.pageType == "service") {
        return tableDataParent.tableData;
      }
      return tableDataParent.tableData.slice((page.pageNum-1) * page.pageSize, page.pageNum * page.pageSize);
    },
    utilElTableConnSelect(url, conf){ // 共通查询
      let self = this;
      // 分页
      var page = self.page;
      if(conf && conf.page) page = eval("self." + conf.page);
      // 请求参数
      var selectParam = self.selectParam;
      if(conf && conf.param) selectParam = eval("self." + conf.param);
      // 参数处理
      var paramData = Object.assign({},selectParam, page);
      if(conf && conf.count) paramData = Object.assign({},paramData,{"pageCount":conf.count});
      if(!conf || conf.init != false) {
        paramData = Object.assign({},paramData,{"pageCount":0,"pageNum":1});
      }
      // 数据体
      var tableDataParent = self;
      if(conf && conf.table) tableDataParent = self[conf.table];
      // 请求查询
      http({
        url: url,
        data: paramData,
        loading: true
      }).then(res => {
        // 判断
        if(res.detail.records){
          page.pageType = "service";
          // 服务器端分页
          if(!conf || conf.init != false) page.pageNum = 1;
          page.pageCount = res.detail.total;
          tableDataParent.tableData = res.detail.records;
        }else {
          page.pageType = "custom";
          // 客户端分页
          page.pageNum = 1;
          page.pageCount = res.detail.length;
          tableDataParent.tableData = res.detail;
        }
        // 回调
        if(conf && conf.fnSucess) conf.fnSucess(res, self);
      });
    },
    //////////////////  图表处理  //////////////////////////////
    // 图表配置
    utilEchartsSetOption(paramType, option, conf, echartsParam){
      let self = this;
      let echartsObj = self.echarts[paramType];
      // 初始化处理
      if(!option) option = {};
      option = tools.mergeObject(echartsObj.option, option);
      var myChart = echartsObj.obj;
      let docId = document.getElementById(echartsObj.id);
      if(!docId) return ;
      if(!myChart) myChart = echartsParam.init(docId);
      myChart.setOption(option);
      // chart对象处理
      echartsObj.obj  = myChart;
      return myChart;
    },
    //////////////////  操作相关  //////////////////////////////
    utilHandleConfirm(paramType, paramData){
      let self = this;
      let confirm = self[paramType];
      // 参数处理
      let message = "确定要执行此操作?";
      if(confirm.message) message = confirm.message;
      let title = "警告";
      if(confirm.title) title = confirm.title;
      // 调出确认框
      self.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning '
      }).then(() => {
        if(confirm.type && confirm.type == "href"){
          let urlParam = "";
          if(paramData){
            let param = Object.assign({},paramData);
            for(var k in param) {
              urlParam = urlParam + "&" + k + "=" + encodeURIComponent(param[k]);
            }
          }
          // 链接跳转
          window.location.href = confirm.url + "?" + urlParam;
        } else {
          // 请求
          http({
            url: confirm.url,
            data: Object.assign({},paramData),
          }).then(res => {
            if(confirm.successFun) confirm.successFun(res, self);
            if(self.fnSelect) self.fnSelect();
          });
        }
      }).catch(() => {});
    },
    // dialog对话框，打开并设置
    utilOpenDialog(paramType, row, config){
      let self = this;
      let dialog = self[paramType];
      if(!dialog) return ;
      for (var key in dialog.param) {
        dialog.param[key] = null;
        if(row && row[key] != null) {
          dialog.param[key] = row[key];
        }
      }
      dialog.visible = true;
    },
    // dialog对话框，参数设置
    utilSetDialog(paramType, config, inParam){
      let self = this;
      let dialog = self[paramType];
      if(!dialog) return ;
      // 设置
      for (var key in dialog.param) {
        if(config && config.clear){
          dialog.param[key] = null;
        }
        if(inParam && inParam[key]){
          dialog.param[key] = inParam[key];
        }
      }
    },
    // dialog对话框，参数设置
    utilSetDialogValue(paramType, key, value){
      let self = this;
      let dialog = self[paramType];
      if(!dialog || !dialog.param) return ;
      dialog.param[key] = value
    },
    // dialog对话框，确认共通对象
    utilDialogBtn(paramType, config) {
      let self = this;
      let dialog = self[paramType];
      if(!dialog) return ;
      if(!config) config = {};

      var dialogParam = Object.assign({},dialog.param);
      if(dialog.checkFun) {
        if(!dialog.checkFun(dialogParam, self)) return;
      }
      self.$refs[dialog.formName].validate((valid) => {
        if (!valid) return ;
        // 参数处理
        for (var varParam in dialogParam) {
          // 列表转换
          if(typeof dialogParam[varParam] == "object" && dialogParam[varParam] && dialogParam[varParam].constructor == Array && dialogParam[varParam].length > 0) {
            if(typeof dialogParam[varParam][0] == "object"){
              // 复制对象转json
              dialogParam[varParam] = JSON.stringify(dialogParam[varParam]);
            }else{
              // 简单对象使用，隔开
              dialogParam[varParam] = dialogParam[varParam].join(",");
            }
          }
        }
        // 请求处理
        if(dialog.url) http({
          url: dialog.url,
          data: Object.assign({},dialogParam),
          methods: config.methods || "post",
          loading: true
        }).then(res => {
          dialog.visible = false;
          if(dialog.successFun) dialog.successFun(res, self);
          if(self.fnSelect) self.fnSelect();
        });
        if(dialog.processFun) dialog.processFun(dialogParam);
      });
    },
    //////////////////  个别共通业务逻辑  //////////////////////////////
    // 共通的登录处理
    utilProcLogin(){
      let self = this;
      // 返回值处理
      if (tools.checkBody(function() {
          tools.check(!!self.loginInfo.account && !!self.loginInfo.password, "请输入用户名和密码！");
        })) return;
      this.axios({
        url: self.requestUrl,
        data: self.loginInfo,
        loading: true
      }).then(res => {
        tools.setLoginToken(JSON.stringify(res.detail));
        // 登录成功
        self.$router.push({path: '/'});
      });
    }
  },
};
export default vueUtil;
